﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;
using Model;
using Common;
using BLL;
using System.Web;

namespace WebPortal.Controllers
{

    public class SysRoleController : BaseController
    {
        private string _aa = "1";
        static private string _competenceRoleId;
        private string _userRoleId;
        private string _targeId;

        #region 对Role操作
        public ActionResult RoleList()
        {
            base.CheckLogin();
            return View();
        }
        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="name">角色名称</param>
        /// <param name="statusStr">状态</param>
        /// <param name="rows"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RoleList(string name, string statusStr, string dbName, int rows = 10, int page = 1)
        {
            base.CheckLogin();
            rows = int.Parse(Request.Params["rows"]);
            page = int.Parse(Request.Params["page"]);
            int statusid = 0;
            if (!string.IsNullOrWhiteSpace(statusStr))
            {
                statusid = int.Parse(statusStr);
            }
            var paras = new SqlParameter[]{
            new SqlParameter("@Name", name),
            new SqlParameter("@Status", statusid),
            new SqlParameter("@DBName", dbName),
            new SqlParameter("@Rows", rows),
            new SqlParameter("@PageNum", page)
            }; 
            var list = SysRoleBLL.GetList(paras);//角色列表
            int count = SysRoleBLL.GetListCount(paras);//总记录数

            //Dictionary<String, Object> jsonDict = new Dictionary<String, Object> { { "total", 1 }, { "rows", list } };

            var jsonDict = new Dictionary<String, Object> { { "total", count }, { "rows", list } };
            return Json(jsonDict);
        }
        #region 旧方法
        public ActionResult RoleAdd()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(SysRoleInfo model)
        {
            base.CheckLogin();
            try
            {
                model.Id = Guid.NewGuid().ToString();
                model.RoleType = 1;
                model.CreateTime = DateTime.Now;
                model.CreatePerson = "superadmin";
                model.IsDelete = 0;
                var bll = new SysRoleBLL();
                bll.Insert(model);

                return RedirectToAction("RoleList", RouteData.Values);
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }

        public ActionResult RoleEdit(string id)
        {
            base.CheckLogin();
            SysRoleInfo model = new SysRoleInfo();
            if (!string.IsNullOrEmpty(id))
                model = SysRoleBLL.GetInfoById(id);
            return View(model);
        }

        [HttpPost]
        public ActionResult UserUpdate(SysRoleInfo model)
        {
            base.CheckLogin();
            try
            {
                if (string.IsNullOrEmpty(model.Id))
                {
                    model.Id = Guid.NewGuid().ToString();
                    model.RoleType = 1;
                    model.CreateTime = DateTime.Now;
                    model.CreatePerson = "superadmin";
                    model.IsDelete = 0;
                    var bll = new SysRoleBLL();
                    bll.Insert(model);
                }
                else
                {
                    model.UpdateTime = DateTime.Now;
                    model.UpdatePerson = "superadmin";
                    model.RoleType = 1;
                    model.IsDelete = 0;
                    var bll = new SysRoleBLL();
                    bll.Update(model);
                }


                return RedirectToAction("RoleList", RouteData.Values);
            }
            catch
            {
                return View();

            }
        }

        public ActionResult DeleteItem(string id)
        {
            base.CheckLogin();
            try
            {
                var bll = new SysRoleBLL();
                var par = new SqlParameter[]
                              {
                                  new SqlParameter("@Id",id),
                                  new SqlParameter("@DeleteUser","superadmin"),
                                  new SqlParameter("@DeleteTime",DateTime.Now),
                                  new SqlParameter("@IsDelete",1)
                              };
                bll.DeleteRow(par);
            }
            catch (Exception)
            {

                throw;
            }
            return View();
        }
        [HttpPost]
        public int ChickCode(string code)
        {
            var par = new SqlParameter[]
                          {
                              new SqlParameter("@Code",code)
                          };
            int count = SysRoleBLL.GetRoleInfoByCode(par);
            return count;
        }
        #region Target
        public ActionResult RoleTarge()
        {
            return View();
        }

        public ActionResult SaveRoleTarge(FormCollection collection, string id)
        {

            var bll = new SysRoleBLL();
            var paras1 = new IDataParameter[1];
            paras1[0] = new SqlParameter("@RoleID", id);
            bll.DeleteTarge(paras1);
            var query = collection["query"].FromJSon<Dictionary<string, string>>();
            foreach (string item in query.Keys)
            {
                if (item != "select_All")
                {
                    string str = query[item];
                    string[] ar = str.Split(',');
                    if (str != "")
                    {
                        var paras = new IDataParameter[6];
                        paras[0] = new SqlParameter("@Guid", Guid.NewGuid());
                        paras[1] = new SqlParameter("@RoleID", id);
                        paras[2] = new SqlParameter("@TargeName", ar[1]);
                        paras[3] = new SqlParameter("@TargeCode", ar[2]);
                        paras[4] = new SqlParameter("@CreateTime", DateTime.Now);
                        paras[5] = new SqlParameter("@CreateUser", "superadmin");
                        bll.InsertTarge(paras);
                    }

                }

            }

            return RedirectToAction("RoleList", RouteData.Values);
        }

        public string RoleTargeView(string id, string dbName)
        {
            var bll1 = new SysRoleBLL();
            var paras1 = new IDataParameter[1];
            paras1[0] = new SqlParameter("@RoleID", id);
            DataTable dt = bll1.SelectTarge(paras1);
            var html = new System.Text.StringBuilder();
            var paras = new IDataParameter[6];
            paras[0] = new SqlParameter("@TargetSysCode", "");
            paras[1] = new SqlParameter("@TargetSysName", "");
            paras[2] = new SqlParameter("@Status", 0);
            paras[3] = new SqlParameter("@TargetType", 0);
            paras[4] = new SqlParameter("@Rows", 100);
            paras[5] = new SqlParameter("@PageNum", 1);
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            EtlTargetSystemBLL bll = new EtlTargetSystemBLL(loginInfos);
            var list = bll.GetList(paras);
            if (list.Count > 0)
            {
                foreach (EtlTargetSystemInfo model in list)
                {
                    bool flg = false;
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        string Code = DBConvert.GetAnsiString(dt.Rows[j], "TargeCode");
                        if (Code == model.TargetSysCode)
                        {
                            flg = true;
                        }
                    }
                    if (!flg)
                    {
                        html.Append(string.Format("<tr id='tr{0}'><td><input type=\"checkbox\" id=\"{0}\" value=\"{0},{1},{2}\" name=\"{1}\" class=\"{2}\" /></td><td>{1}</td><td>{2}</td></tr>", model.GUID, model.TargetSysName, model.TargetSysCode));
                    }
                    else
                    {
                        html.Append(string.Format("<tr id='tr{0}'><td><input type=\"checkbox\" checked=\"checked\" id=\"{0}\" value=\"{0},{1},{2}\" name=\"{1}\" class=\"{2}\" /></td><td>{1}</td><td>{2}</td></tr>", model.GUID, model.TargetSysName, model.TargetSysCode));
                    }


                }
            }
            return html.ToString();
        }

        #endregion
        #endregion
        #endregion

        #region 编辑角色菜单权限

        public ActionResult Competence(string id)
        {
            base.CheckLogin();
            var menuInfo = new SysIDMenuInfo { Id = id };
            _competenceRoleId = id;
            return View();
        }
        /// <summary>
        /// 保存权限
        /// </summary>
        /// <param name="strs">提交值</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveCompetence(string strs)
        {
            base.CheckLogin();
            try
            {
                string id = _competenceRoleId;
                var str = strs.Split(',');
                var bll = new SysRoleBLL();
                var paras1 = new IDataParameter[1];
                paras1[0] = new SqlParameter("@RoleID", id);
                bll.DeleteCompetence(paras1);
                foreach (var str1 in str)//菜单列表
                {
                    var paras = new IDataParameter[5];
                    paras[0] = new SqlParameter("@Guid", Guid.NewGuid());
                    paras[1] = new SqlParameter("@RoleID", id);
                    paras[2] = new SqlParameter("@MunItem", str1);
                    paras[3] = new SqlParameter("@CreateTime", DateTime.Now);
                    paras[4] = new SqlParameter("@CreateUser", "superadmin");
                    bll.InsertCompetence(paras);
                }

                return Json("OK");
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }

        /// <summary>
        /// 获取树形页面的数据
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTree()
        {
            base.CheckLogin();
            var menuInfo = new SysIDMenuInfo();
            string id = _competenceRoleId;
            var bll1 = new SysRoleBLL();
            var paras1 = new IDataParameter[1];
            paras1[0] = new SqlParameter("@RoleID", id);
            DataTable dt = bll1.SelectCompetence(paras1);

            var listSystemTree = new List<SystemTree>();

            //IBLL.ISysMenuBLL db = new SysMenuBLL();

            var tree = new SysMenuTreeNodeCollection();
             
            var trees = SysMenuBLL.GetInfoList();//树菜单列表
            if (trees != null)
            {

                string parentId = Request["parentid"];//父节点编号
                if (string.IsNullOrWhiteSpace(parentId))
                {
                    //tree.Bind(trees, null, ref listSystemTree, dt, "");
                }
                else
                {
                    //tree.Bind(trees, parentId, ref listSystemTree, dt, "");
                }
            }
            JsonResult jr = Json(listSystemTree, JsonRequestBehavior.AllowGet);
            return jr;
        }
        #endregion

        #region 编辑组用户
        public ActionResult RoleUser(string id)
        {
            base.CheckLogin();
            _userRoleId = id;
            return View();
        }

        /// <summary>
        /// 已保存组用户列表
        /// </summary>
        /// <param name="id">组id</param>
        /// <returns></returns>
        public string selectUser(string id)
        {
            base.CheckLogin();
            var paras1 = new IDataParameter[1];
            paras1[0] = new SqlParameter("@RoleID", id);
            var bll = new SysRoleBLL();
            DataTable dt = bll.SelectUser(paras1);//已保存组用户列表
            List<SysUserInfo> list = new List<SysUserInfo>();
            System.Text.StringBuilder html = new System.Text.StringBuilder();
            foreach (DataRow dr in dt.Rows)//渲染页面html
            {
                string disable = string.Empty;
                if (id == "0fbb1ac4-ea73-42a5-b5a2-20a14d892cdc")//超级管理员
                {
                    //超级管理员不可编辑自己
                    if ("superadmin".ToLower() == dr["UserCode"].ToString().ToLower() || Request.Cookies["MDM_RoleID"].Value.ToLower() != id)
                        disable = " disabled='disabled'";
                }
                //管理员不可编辑所有人
                if (id == "3370c724-23d9-41a1-a281-6e4ccff478eb" && Request.Cookies["MDM_RoleID"].Value.ToLower() == id)
                {
                    disable = " disabled='disabled'";
                }
                html.Append(string.Format("<tr id='tr1{0}'><td><input type=\"checkbox\" id=\"{0}\" value=\"{0},{1},{2}\" name=\"{0},{1},{2}\" class=\"{2}\" {3}/></td><td>{1}</td><td>{2}</td></tr>",
                    dr["Guid"], dr["UserName"], dr["UserCode"], disable));
            }
            return html.ToString();
        }
        /// <summary>
        /// 保存用户组
        /// </summary>
        /// <param name="collection">提交数据</param>
        /// <param name="id">组id</param>
        /// <returns></returns>
        public ActionResult SaveRoleUser(FormCollection collection, string id)
        {
            base.CheckLogin();
            try
            {
                var bll = new SysRoleBLL();
                var paras1 = new IDataParameter[1];
                paras1[0] = new SqlParameter("@RoleID", id);
                bll.DeleteUser(paras1);//删除组内用户
                var query = collection["query"].FromJSon<Dictionary<string, string>>();

                foreach (string item in query.Keys)
                {
                    if (item != "select_All")
                    {
                        string str = item;
                        string[] ar = str.Split(',');
                        var paras = new IDataParameter[6];
                        paras[0] = new SqlParameter("@Guid", Guid.NewGuid());
                        paras[1] = new SqlParameter("@RoleID", id);
                        paras[2] = new SqlParameter("@UserName", ar[1]);
                        paras[3] = new SqlParameter("@UserCode", ar[2]);
                        paras[4] = new SqlParameter("@CreateTime", DateTime.Now);
                        paras[5] = new SqlParameter("@CreateUser", "superadmin");
                        bll.InsertUser(paras);//添加组用户
                    }

                }
                return RedirectToAction("RoleList", RouteData.Values);
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
        #endregion

    }
}
